<!--
 * @Author: JiuHuiGong
 * @Date: 2022-04-01 10:45:49
 * @LastEditTime: 2023-07-05 16:25:23
 * @LastEditors: Please set LastEditors
 * @Description:文件上传组件 支持拍照 version1.0
 使用方式:
 1 引入import upload from "@/components/upload/upload";
  <upload  iconType="fj"
   @fileChange="fileChange"
  :fileIds="fileIds"</upload>
 2  父组件定义方法
  data{
   fileChange(ids){
      console.log("父组件"+ids) //你要保存的fileids
      
    },
  }

3 showUpload 控制是否展示上传区域 删除按钮
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\components\upload\upload.vue
-->
<template>
  <div class="upload">
    <div class="uploadtitle" v-if="showUpload">
      <span class="title">{{ titleName }}</span>
      <van-uploader :after-read="afterRead" :before-delete="beforeDelete" :max-size="10 * 1024 * 1024" @oversize="onOversize" @click-preview="click_preview"
        :max-count="2" :accept="fileType" :disabled="isDone" :show-upload="showUpload" :multiple="multiple" :preview-image="false">
        <img class="uplimg" v-if="iconType == 'fj'" src="@/assets/img/fujian.png" />
      </van-uploader>
    </div>
    <div class="uploadcontent" v-if="showUpload">
      <div class="filerows" v-for="(item, index) in fileList" :key="index">
        <span class="filename" @click="click_preview(item)">{{
          item.fileName
        }}</span>
        <img class="uplimg" @click="deleteFile(index)" src="@/assets/img/2.png" v-if="showUpload" />
        <span class="operation" v-if="!showUpload" @click="click_preview(item)">查看</span>
      </div>
    </div>

    <div class="uploadcontent" v-if="!showUpload">
      <div class="filerows2" v-for="(item, index) in fileList" :key="index">
        <span class="filename" @click="click_preview(item)">{{
          item.fileName
        }}</span>
        <img class="uplimg" @click="deleteFile(index)" src="@/assets/img/2.png" v-if="showUpload" />
        <span class="operation" v-if="!showUpload" @click="click_preview(item)">查看</span>
      </div>
    </div>
    <div class="preview-cover" v-if="filePreviewShow"><img :src="uri" /></div>
  </div>
</template>
<script>
import { getAction, uploadAction, postAction } from "@/api/manage";
import { apiBaseUrlDownload, apiBaseUrlUpload } from "@/utils/request";
import { ImagePreview } from "vant";
export default {
  created() {},
  props: {
    id: String,
    fileUrl: Array,
    type: Number,
    isDone: Boolean,
    fileType: {
      type: String,
      default: "",
    }, //定义图标样式不传
    fileIds: {
      type: String,
      default: "",
    }, //父子组件需要传递的值
    titleName: {
      type: String,
      default: "附件",
    },
    maxCount: {
      type: Number,
      default: 5,
    }, //最大上传数量
    multiple: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域 //开启多选
    iconType: {
      type: String,
      default: "",
    }, //定义上传组件图标 空时默认  换图标自己在slot里加
    showUpload: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域
  },
  data() {
    return {
      filePreviewShow: false,
      uri: "",
      fileList: [],
      //   fileListImagList: [],
    };
  },
  watch: {
    fileIds: {
      handler(newVal, oldVal) {
        if (this.showUpload == false) {
          this.initFileList();
        } else {
          if (newVal == "") {
            this.fileList = [];
          } else {
            this.initFileList();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    console.log("fileIds1" + this.fileIds);
    // if (this.fileIds) {
    //   this.initFileList();
    // }
  },
  methods: {
    initFileList() {
      // if(this.fileIds==""){
      //   this.fileList=[]
      //   return
      // }
      console.log("fileIds1" + this.fileIds);
      let ids = [];
      ids = this.fileIds ? this.fileIds.split(",") : [];
      this.fileList = [];
      ids.forEach((item) => {
        let params = { id: item };
        getAction("/public/pubAttachmentFile/queryById", params).then((res) => {
          if (res.success) {
            // console.log("sssss"+that_.fileList)
            let obj = res.result;
            obj.uri = "/sys/common/static/" + obj.uri;
            // console.log(obj.uri);
            this.fileList.push(obj);
          }
        });
      });
    },
    // 文件超过大小
    onOversize(file) {
      //   console.log(file);
      this.$toast("文件大小不能超过 10M");
    },
    /**文件上传 */
    afterRead(file) {
      let that_ = this;

      if (this.fileList.length >= this.maxCount && this.maxCount != "-1") {
        this.$toast("最多上传" + this.maxCount + "个文件");
        return;
      }
      var formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      formData.append("file", file.file);
      formData.append("biz", "temp");
      uploadAction("/sys/common/upload2", formData).then((res) => {
        if (res.success) {
          // console.log("sssss"+that_.fileList)

          that_.fileList.push(res.result);

          this.fileChange();
        }
      });
      //   console.log(this.fileList);
    },
    /**文件删除 */
    beforeDelete(file, detail) {},
    /* 文件下载 */
    click_preview(item) {
      // console.log(item);
      var reg = /\w*(?=\/)/;
      // console.log(item.mediaType.match(reg)[0],item.mediaType)
      // return
      if (item.mediaType.match(reg)[0] == "image") {
        this.uri = apiBaseUrlDownload + 'jksaas-mgt/mgt' + item.uri;
        console.log(this.uri);
        console.log(item.mediaType.match(reg)[0], item.mediaType);
        ImagePreview({
          images: [this.uri],
          startPosition: 0,
          closeable: true,
        });
      } else {
        location.href = apiBaseUrlDownload + item.uri;
      }
    },
    /* 删除文件*/
    deleteFile(index) {
      // console.log(index);
      this.fileList.splice(index, 1);
      //    arr.splice(arr.findIndex(item => item.id === data.id), 1)
      this.fileChange();
    },
    fileChange() {
      let ids = "";
      this.fileList.forEach((item, index) => {
        // console.log(item);
        if (index == this.fileList.length - 1) {
          ids = ids + item.id;
        } else {
          ids = ids + item.id + ",";
        }
      });
      this.$emit("fileChange", ids);
    },
  },
};
</script>

<style lang="scss" scoped>
.upload {
  // margin-bottom: 0.1rem;
  .uploadtitle {
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.17rem;

    .title {
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
    }
  }
  .uploadcontent {
    background: #ffffff;
    .filerows {
      display: flex;
      justify-content: space-between;
      padding: 0.17rem;
      .operation {
        font-size: 0.14rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }
    .filerows2 {
      display: flex;
      justify-content: space-between;
      // padding: 0.17rem;
      // border:1px solid red;
      padding-bottom: 0.15rem;
      .operation {
        font-size: 0.14rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }
  }
}

.uplimg {
  width: 0.18rem;
  height: 0.18rem;
}
.filename {
  width: 2rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>